package com.meihua.baoleyi.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.meihua.baoleyi.R;
import com.meihua.baoleyi.base.BaseActivity;
import com.meihua.baoleyi.common.APIServer;
import com.meihua.baoleyi.net.RegisterC;
import com.meihua.baoleyi.utils.CountDownTimerUtils;
import com.meihua.baoleyi.utils.RegularConstant;
import com.meihua.baoleyi.utils.StringUtils;
import com.meihua.baoleyi.utils.ToastUtils;
import com.meihua.baoleyi.utils.UrlContants;
import com.meihua.baoleyi.utils.ValidateHelper;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

import static com.meihua.baoleyi.utils.StringUtils.isOrderNumeric;
import static com.meihua.baoleyi.utils.StringUtils.isOrderNumeric_;


/**
 * Name: liming
 * Time: 2017/10/16.
 * 注册页面
 */

public class RegisterActivity extends BaseActivity implements View.OnClickListener {
    private static Toast toast;
    @Bind(R.id.left_img)
    RelativeLayout leftImg;
    @Bind(R.id.right_text)
    TextView rightText;
    private EditText register_phone, register_code, register_pwd;
    private Button get_code;
    private Button button;
    private CheckBox checkBoxNew;
    private RegisterC mFreeNightPresenter;
    private TextView tv_Read;
    String phoneNum;
    String password;
    String code;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        ButterKnife.bind(this);
        onInitView();
    }

    public void onInitView() {
        tv_Read = (TextView) findViewById(R.id.tv_Read);
        checkBoxNew = (CheckBox) findViewById(R.id.checkBoxNew);
        register_phone = (EditText) findViewById(R.id.register_phone);
        register_code = (EditText) findViewById(R.id.register_code);
        get_code = (Button) findViewById(R.id.get_code);
        register_pwd = (EditText) findViewById(R.id.register_pwd);
        button = (Button) findViewById(R.id.register_submit);
        get_code.setOnClickListener(this);
        tv_Read.setOnClickListener(this);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                phoneNum = register_phone.getText().toString().trim();
                password = register_pwd.getText().toString().trim();
                code = register_code.getText().toString().trim();
                if (password.length() < 8) {
                    Toast.makeText(RegisterActivity.this, "密码长度不能小于8", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (password.matches(RegularConstant.RGX_ALL_NUMBER)) {
                    Toast.makeText(RegisterActivity.this, "不能输入纯数字", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (password.matches(RegularConstant.RGX_ALL_LETTER)) {
                    Toast.makeText(RegisterActivity.this, "不能输入纯字母", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (StringUtils.equalStr(password)) {
                    Toast.makeText(RegisterActivity.this, "不能全是相同的数字或者字母", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (isOrderNumeric(password) || isOrderNumeric_(password)) {
                    Toast.makeText(RegisterActivity.this, "不能是连续的数字--递增或递减", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!checkBoxNew.isChecked()) {
                    Toast.makeText(RegisterActivity.this, "请确认是否阅读完用户注册协议", Toast.LENGTH_SHORT).show();
                    return;
                }
                click_submit();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.get_code://获取验证码
                getVerifyCode();
                break;
            case R.id.tv_Read:
                Intent intent1 = new Intent(this, CommonWebActivity.class);
                intent1.putExtra("url", APIServer.REGISTRATION);
                startActivity(intent1);
                break;
        }
    }

    @OnClick({R.id.title_iv_back, R.id.left_img, R.id.right_text})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_iv_back: //返回
                finish();
                break;
            case R.id.right_text:
                Intent intent = new Intent(this, MainActivity.class);
                startActivity(intent);
                break;
        }
    }

    public static void showShortCenter(Context context, int content) {
        if (toast == null) {
            toast = Toast.makeText(context, content, Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
        } else {
            toast.setText(content);
            toast.setGravity(Gravity.CENTER, 0, 0);
        }
        toast.show();
    }

    public boolean isEmpty(String str) {
        return str == null || "".equals(str.trim()) || "null".equals(str);
    }

    /**
     * 获取验证码
     */
    public void getVerifyCode() {
        if (isEmpty(register_phone.getText().toString().trim())) {
            showShortCenter(this, R.string.input_phone);
            return;
        }
        CountDownTimerUtils countDownTimerUtils = new CountDownTimerUtils(RegisterActivity.this, get_code, 60000, 1000);
        countDownTimerUtils.start();
        phoneNum = register_phone.getText().toString().trim();
        boolean result = ValidateHelper.isPhoneNumberValid(phoneNum);
        if (!result) {
            Toast.makeText(this, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        OkGo.get(UrlContants.REGIST_SEND_CODE)
                .tag(this)
                .params("phone", phoneNum)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        if (s != null) {
                            try {
                                JSONObject jsonObject = new JSONObject(s);
                                if (jsonObject.optString("code").equals("200")) {
                                    ToastUtils.showT(RegisterActivity.this, "发送验证码成功！");
                                } else {
                                    String message = jsonObject.getString("msg");
                                    ToastUtils.showT(RegisterActivity.this, message);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                    }
                });
    }

    //注册
    private void click_submit() {
        OkGo.post(UrlContants.URL_REGIST)
                .tag(this)
                .params("user_phone", phoneNum)
                .params("user_password", password)
                .params("code", code)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        if (s != null) {
                            try {
                                JSONObject jsonObject = new JSONObject(s);
                                if (jsonObject.optString("code").equals("200")) {
                                    startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
                                } else {
                                    ToastUtils.showT(RegisterActivity.this, "注册失败！");
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                    }
                });
    }
}